import _ from 'lodash'

export default {
  props: {
    // 最大选项
    maxCount: {
      type: Number,
      default: () => 0,
    },

    // 最小选项
    minCount: {
      type: Number,
      default: () => 0,
    },

    // 选择value
    checkValue: {
      type: Array,
      default: () => [],
    },
  },

  watch: {
    value: {
      immediate: true,
      handler (val) {
        this.inputValue = val
      },
    },

    // checkValue
    checkValue: {
      immediate: true,
      handler (val) {
        this.valueList = val
      },
    },
  },

  methods: {
    // change
    handleChange (val) {
      this.onChange(val)
      this.validate()
    },

    // 表单验证
    validate (option = { first: true }) {
      return new Promise((resolve, reject) => {
        this.errorMessage = ''
        this.$nextTick(async () => {
          if (this.canDo) {
            resolve(true)
            return false
          }

          const ref = 'vanSelectInput'
          const _validateList = [this.createSchema(option)]

          // select input
          _.forEach(this.option, ({ field_value, has_fill }, i) => {
            const index = this.inputValue.indexOf(field_value)
            if (index > -1 && has_fill) {
              const { createSchema } = this.$refs[ref + i][0]
              createSchema && _validateList.push(createSchema(option))
            }
          })
          try {
            await Promise.all(_validateList)
            resolve(true)
          } catch ({ errors: [{ message }] }) {
            this.errorMessage = message
            reject({ message, dom: this.refCustomForm })
          }
        })
      })
    },
  },
}
